How to 'listen' for the event that a variable has been declared/created?
From CSS I know that I can fire upon availibility of a CSS class like this:
let logo = document.querySelector('.test');
logo.addEventListener('load', (event) => {
console.log('CSS class .test is defined now!');
});
Analogously to that I am looking for a 'querySelector' for variables, something like:
logo = window.hasOwnProperty('window.myVariable');
logo.addEventListener('load', (event) => {
console.log('window.myVariable is defined now!');
});
Usage: I want to fire code as soon as an externally async loaded script has established the variable in question.
EDIT: some background In my web page (code I controll) I am loading a 3rd party .js script from another domain (code I don't controll). That script than loads more code from its domain. This 2nd script establishes a variable 'window.something { "key":"value",...} and then issues the loading of a third script. I want to interact with my js code to patch the variable as soon as it is available and before the 3rd script is executed. @reyno suggested the use of Proxy. My latest approach is to establish the variable myself and then watch for changes using Proxy.
<body>
<script>
// establish variable
window.someVariable={"someKey":"someValue"};
// set up Proxy listener:
var targetProxy = new Proxy(window.someVariable,{
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
// change occured, thus 3rd party set values
// ... add more code here ...
return true;
}
});
// test:
console.log(window.someVariable);
window.someVariable.someKey="NEW CONTENT";
console.log(window.someVariable);
</script>
<!-- load the external script -->
<script src="https://"></script>
<!-- rest of html page ... -->
</body>
The problem now is that the other software, running in its own pop up window, looks like having its own scope, an 'own' window.someVariable, not overwriting mine.
First, set a custom event listener, I like to call it "notify".
document.addEventListener("notify", function() {
console.log('window.myVariable is defined now!');
})
In your script that will load later, trigger this event listener when your variable is created.
const myVariable = "hello world";
document.dispatchEvent(new Event("notify"));